﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using Looptribe.Moodlin8.Model;
using Looptribe.WinRT.Toolkit;

namespace Looptribe.Moodlin8.ViewModel
{
    public class CourseUsersViewModel : LoadingViewModel
    {
        private Course _course;
        public Course Course
        {
            get { return _course; }
            set { Set(() => Course, ref _course, value); }
        }

        private readonly ObservableCollection<CourseUserWrapper> _users = new ObservableCollection<CourseUserWrapper>();
        public ObservableCollection<CourseUserWrapper> Users { get { return _users; } }

        private readonly ObservableCollection<GroupInfoList<CourseUserWrapper>> _groupedUsers = new ObservableCollection<GroupInfoList<CourseUserWrapper>>();
        public ObservableCollection<GroupInfoList<CourseUserWrapper>> GroupedUsers { get { return _groupedUsers; } }

        public ICommand GotoUserCommand { get; private set; }

        public CourseUsersViewModel()
        {
            GotoUserCommand = new RelayCommand<CourseUserWrapper>(ExecuteGotoUser, a => a != null && a.User.Id != CurrentUser.Id);
        }

        private void ExecuteGotoUser(CourseUserWrapper wrapper)
        {
            Controller.GotoUserMessages(wrapper.User.ToUser());
        }

        public async Task LoadContent(Course course)
        {
            Course = course;

            IsLoading = true;
            var content = (await Api.GetCourseEnrolledUsersAsync(course.Id)).Data;
            IsLoading = false;

            Users.Clear();
            Users.AddMany(content
                .Where(user => user.Roles.Any(role => role.Shortname.ToLower().Equals(UserRole.Student)))
                .Select(user => new CourseUserWrapper(user)));

            GroupedUsers.Clear();
            var query = Users.OrderBy(u => u.User.Fullname)
                .GroupBy(u => u.User.Fullname[0], u => u)
                .Select(g => new {GroupName = g.Key, Items = g});
            foreach (var g in query)
            {
                var info = new GroupInfoList<CourseUserWrapper> {Key = g.GroupName};
                foreach (var item in g.Items)
                    info.Add(item);
                GroupedUsers.Add(info);
            }
        }
    }
}
